package com.tianji.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.RandomUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.config.SessionProperties;
import com.tianji.domain.po.ChatSession;
import com.tianji.domain.vo.ChatHistoryVO;
import com.tianji.domain.vo.SessionVO;
import com.tianji.mapper.ChatSessionMapper;
import com.tianji.service.ChatSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements ChatSessionService {
    @Autowired
    private SessionProperties sessionProperties;

    @Override
    public SessionVO returnQuestion(Integer n) {
        //新增会话
        String sessionId = IdUtil.fastSimpleUUID();
        ChatSession chatSession = ChatSession.builder().sessionId(sessionId).userId(UserContext.getUser()).title(null)
                .build();
        save(chatSession);
        //返回对象
        SessionVO sessionVO = BeanUtils.toBean(sessionProperties, SessionVO.class);
        sessionVO.setSessionId(sessionId);
        sessionVO.setExamples(RandomUtils.randomEleList(sessionVO.getExamples(), n));

        return sessionVO;
    }

    @Override
    public List<SessionVO.Example> getHotQuestions(Integer n) {
        return RandomUtils.randomEleList(sessionProperties.getExamples(), n);
    }

    @Async("wscDaHaoRenExecutor")
    @Override
    public void updateChatSessionTittle(String sessionId, String tittle, Long userId) {
        //先查询
        ChatSession chatSessionDb = lambdaQuery().eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, userId)
                .isNull(ChatSession::getTitle)
                .one();
        log.info("开始睡觉");
        if (chatSessionDb == null) {
            return;
        }
        chatSessionDb.setTitle(StrUtil.sub(tittle, 0, 20));
        chatSessionDb.setUpdateTime(LocalDateTime.now());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("已经睡醒了");
        updateById(chatSessionDb);
    }

    @Override
    public Map<String, List<ChatHistoryVO>> getHistoryRecord() {
        String now="当天";
        String month="最近30天";
        String lessYear="最近一年";
        String overYear="一年以上";
        //查询数据库中的数据
        List<ChatSession> list = lambdaQuery().eq(ChatSession::getUserId, UserContext.getUser())
                .isNotNull(ChatSession::getTitle)
                .orderByDesc(ChatSession::getUpdateTime)
                .list();

        return list.stream().map(m -> ChatHistoryVO.builder()
                .updateTime(m.getUpdateTime())
                .sessionId(m.getSessionId())
                .title(m.getTitle())
                .build()

        ).collect(Collectors.groupingBy((SFunction<ChatHistoryVO, String>) chatHistoryVO -> {
            LocalDateTime updateTime = chatHistoryVO.getUpdateTime();
            LocalDateTime now1 = LocalDateTime.now();
            long day = LocalDateTimeUtil.between(updateTime, now1, ChronoUnit.DAYS);
            if (day < 1) {
                return now;
            } else if (day <= 30) {
                return month;
            } else if (day <= 365) {
                return lessYear;
            } else {
                return overYear;
            }
        }));
    }
}
